from flask import Flask, request, jsonify  # flask库
import time
from flask_cors import CORS

from algorithm import compKey
from sql import *

app = Flask(__name__)  # 创建一个服务，赋值给APP
CORS(app, resource=r'/*')

# 获取竞争性关键字
@app.route('/search', methods=['GET'])  # 指定接口访问的路径，支持什么请求方式get，post
# 定义的方法名必须和接口路径相同
# 由于路径是'/test'，所以方法名为test()
# 浏览器直接访问直接为'Get'方法
def test():
    keyword = request.args.get("keyword")

    print("keyword:", keyword)
    comp_word, midwords_info_list, weight_dict, word_Statistics = compKey(keyword)
    response_data = {
        "SystemTimeObject": {
            "VIIDServerID": "123",
            "TimeMode": "1",
            "LocalTime": time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())),
            "comp_word": comp_word,
            "midwords_info_list": midwords_info_list,
            "weight_dict": weight_dict,
            "word_statistics": word_Statistics
        }
    }
    return jsonify(response_data['SystemTimeObject'])

# 获取推荐关键字
@app.route('/search/recommend', methods=['GET'])  # 指定接口访问的路径，支持什么请求方式get，post
# 定义的方法名必须和接口路径相同
# 由于路径是'/test'，所以方法名为test()
# 浏览器直接访问直接为'Get'方法
def get_recommend():
    userid = request.args.get("userid")

    comp_word, midwords_info_list, weight_dict = recommend_list(userid)
    response_data = {
        "SystemTimeObject": {
            "VIIDServerID": "123",
            "TimeMode": "1",
            "LocalTime": time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())),
            "comp_word": comp_word,
            "record_word": midwords_info_list,
            "record_word_weight_dict": weight_dict
        }
    }
    return jsonify(response_data['SystemTimeObject'])


# 获取用户的搜索记录
@app.route('/search/record', methods=['GET'])  # 指定接口访问的路径，支持什么请求方式get，post
# 定义的方法名必须和接口路径相同
# 由于路径是'/test'，所以方法名为test()
# 浏览器直接访问直接为'Get'方法
def search_record():
    userid = request.args.get("userid")

    search_list = get_search_record(userid)
    response_data = {
        "SystemTimeObject": {
            "VIIDServerID": "123",
            "TimeMode": "1",
            "LocalTime": time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())),
            "record": search_list
        }
    }
    return jsonify(response_data['SystemTimeObject'])



if __name__ == '__main__':
    # 这个host：windows就一个网卡，可以不写，而linux有多个网卡，写成0.0.0.0可以接受任意网卡信息
    # 端口号默认5000，可以手动设置，这里我设置成了8802
    app.run(host='0.0.0.0', port=8802, debug=True)
